package com.ssm.threadPool;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 功能描述: 项目执行线程的线程池操作类，需要执行的线程，可以通过该类进行submit提交执行
 * 该类中管理了线程池进行执行线程。
 *
 * @author lixiaomeng
 * @date 2018/12/3
 */
public class AppliactionThreadPoolExecutor {

    private ExecutorService threadExecutor = null;

    private static AppliactionThreadPoolExecutor threadPoolExecutor;

    private AppliactionThreadPoolExecutor(){
        threadExecutor = Executors.newFixedThreadPool(12);
    }


    public static AppliactionThreadPoolExecutor getInstanceThreadPoolExecutor() {
        if (threadPoolExecutor == null) {
            threadPoolExecutor = new AppliactionThreadPoolExecutor();

        }
        return threadPoolExecutor;
    }

    /**
     *
     * 功能描述: 提交线程池，执行一个Callable，返回Future
     *
     * @param: [callable]
     * @return: java.util.concurrent.Future
     * @author: lixiaomeng
     * @time: 2018/12/4 13:53
     */
    public Future submitCall(Callable callable) {
        Future future = threadExecutor.submit(callable);
        return future;
    }

    public void submitRunable(Runnable runnable) {
        threadExecutor.submit(runnable);
    }

    public void submitRunable(Runnable runnable, Object result) {
        threadExecutor.submit(runnable,result);
    }

    private void closePool() {
        System.out.println("线程池要关闭了.....");
        if (threadExecutor.isShutdown() == false) {
            threadExecutor.shutdown();
        }
        System.out.println("线程池关闭完成以后的状态是：" + threadExecutor.isShutdown());
        System.out.println("线程池关闭完成以后的状态是isTerminated：" + threadExecutor.isTerminated());

    }

    /**
     *
     * 功能描述:  关闭线程池操作
     *
     * @param: []
     * @return: void
     * @author: lixiaomeng
     * @time: 2018/12/4 14:38
     */
    public static void closedThreadPool() {
        System.out.println("关闭线程池");
        if (threadPoolExecutor != null) {
            System.out.println("线程池非空");
            threadPoolExecutor.closePool();
        }
    }


    public static void main(String[] args) throws Exception {


        Future future = AppliactionThreadPoolExecutor.getInstanceThreadPoolExecutor().submitCall(() -> {
            System.out.println("Callable的执行，要sleep了");
            Thread.sleep(2000);
            return "这是线程返回的数据";
        });

        System.out.println("主线程继续执行数据........");
        System.out.println("这是主线程的执行顺序结果");
        System.out.println(future.get());

    }

}
